package com.qy.controller.app;

import com.qy.base.core.*;
import com.qy.base.utils.DateUtil;
import com.qy.base.utils.weixin.utils.PayCommonUtil;
import com.qy.base.utils.weixin.utils.WXAPPConfigUtil;
import com.qy.model.*;
import com.qy.service.*;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by zaq on 2018/07/10.
 */
@RestController
@RequestMapping("/app/policy/order")
public class PolicyOrderController {
    @Resource
    private PolicyOrderService policyOrderService;

    @Resource
    private MemberService memberService;

    @Resource
    private MemberOrderService memberOrderService;

    @Resource
    private PolicyService policyService;

    @Resource
    private UnitService unitService;

    @Resource
    private ChargeService chargeService;

    @Resource
    private MessageService messageService;

    @PostMapping("/add")
    public Result add(@RequestBody PolicyOrder policyOrder) {
        policyOrderService.save(policyOrder);
        return ResultGenerator.successResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Integer id) {
        policyOrderService.deleteById(id);
        return ResultGenerator.successResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody PolicyOrder policyOrder) {
        policyOrderService.update(policyOrder);
        return ResultGenerator.successResult();
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        PolicyOrder policyOrder = policyOrderService.findById(id);
        return ResultGenerator.successResult(policyOrder);
    }

    @GetMapping("/list")
    public Result list(PageBean<PolicyOrder> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<PolicyOrder> list = policyOrderService.findAll();
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //购买
    @PostMapping("/buy")
    public Result buy(@RequestBody PolicyOrder policyOrder) {
        if (policyOrder.getUser_id() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }

        DecimalFormat decimalFormat = new DecimalFormat("0.00");

        Member member = memberService.findById(policyOrder.getUser_id());

        if (policyOrder.getBuy_form() == 1) {
            if (policyOrder.getBuy_type() == 1) {
                Policy policy = policyService.findById(policyOrder.getPolicy_id());
                if (policy.getUser_id() != null) {
                    Member member1 = memberService.findById(policy.getUser_id());
                    Message message = new Message();
                    message.setUser_id(member1.getId());
                    message.setMessage_type(5);
                    message.setMessage_content(member.getNickname() + "购买了您发布的政策");
                    message.setMessage_port(1);
                    message.setAdd_time(DateUtil.getNowTimestamp());
                    messageService.save(message);
                }
                member.setPolicy_surplus_number(member.getPolicy_surplus_number() - 1);
            } else if (policyOrder.getBuy_type() == 2) {
                Unit unit = unitService.findById(policyOrder.getUnit_id());
                if (unit.getUser_id() != null) {
                    Member member1 = memberService.findById(unit.getUser_id());
                    Message message = new Message();
                    message.setUser_id(member1.getId());
                    message.setMessage_type(5);
                    message.setMessage_content(member.getNickname() + "购买了您发布的政策");
                    message.setMessage_port(1);
                    message.setAdd_time(DateUtil.getNowTimestamp());
                    messageService.save(message);
                }
                member.setUnit_surplus_number(member.getUnit_surplus_number() - 1);
            } else if (policyOrder.getBuy_type() == 3) {
                Charge charge = chargeService.findById(policyOrder.getCharge_id());
                if (charge.getUser_id() != null) {
                    Member member1 = memberService.findById(charge.getUser_id());
                    Message message = new Message();
                    message.setUser_id(member1.getId());
                    message.setMessage_type(5);
                    message.setMessage_content(member.getNickname() + "购买了您发布的政策");
                    message.setMessage_port(1);
                    message.setAdd_time(DateUtil.getNowTimestamp());
                    messageService.save(message);
                }
                member.setCharge_surplus_number(member.getCharge_surplus_number() - 1);
            }
        } else if (policyOrder.getBuy_form() == 3) {

            member.setMember_surplus_number(member.getMember_surplus_number() - 1);

            List<MemberOrder> list = memberOrderService.selectMemberOrderByUserId(member);
            Double amount;
            if (list.size() == 0) {
                amount = 0.00;
            } else {
                MemberOrder memberOrder = list.get(0);
                amount = Double.valueOf(memberOrder.getAmount()) / Double.valueOf(memberOrder.getBars_number());
            }
            policyOrder.setAmount(decimalFormat.format(amount));

            if (policyOrder.getBuy_type() == 1) {
                Policy policy = policyService.findById(policyOrder.getPolicy_id());
                if (policy.getUser_id() != null) {
                    Member member1 = memberService.findById(policy.getUser_id());
                    member1.setBalance(String.valueOf(Double.valueOf(member1.getBalance()) + (amount / 2.0)));
                    memberService.update(member1);
                    Message message = new Message();
                    message.setUser_id(member1.getId());
                    message.setMessage_type(5);
                    message.setMessage_content(member.getNickname() + "购买了您发布的政策");
                    message.setMessage_port(1);
                    message.setAdd_time(DateUtil.getNowTimestamp());
                    messageService.save(message);
                }
            } else if (policyOrder.getBuy_type() == 2) {
                Unit unit = unitService.findById(policyOrder.getUnit_id());
                if (unit.getUser_id() != null) {
                    Member member1 = memberService.findById(unit.getUser_id());
                    member1.setBalance(String.valueOf(Double.valueOf(member1.getBalance()) + (amount / 2.0)));
                    memberService.update(member1);
                    Message message = new Message();
                    message.setUser_id(member1.getId());
                    message.setMessage_type(5);
                    message.setMessage_content(member.getNickname() + "购买了您发布的政策");
                    message.setMessage_port(1);
                    message.setAdd_time(DateUtil.getNowTimestamp());
                    messageService.save(message);
                }
            } else if (policyOrder.getBuy_type() == 3) {
                Charge charge = chargeService.findById(policyOrder.getCharge_id());
                if (charge.getUser_id() != null) {
                    Member member1 = memberService.findById(charge.getUser_id());
                    member1.setBalance(String.valueOf(Double.valueOf(member1.getBalance()) + (amount / 2.0)));
                    memberService.update(member1);
                    Message message = new Message();
                    message.setUser_id(member1.getId());
                    message.setMessage_type(5);
                    message.setMessage_content(member.getNickname() + "购买了您发布的政策");
                    message.setMessage_port(1);
                    message.setAdd_time(DateUtil.getNowTimestamp());
                    messageService.save(message);
                }
            }


        }
        memberService.update(member);

        Random random = new Random();
        String content = String.valueOf(random.nextInt(9999) % (9999 - 1000 + 1) + 1000);
        String randomOrderNum = DateUtil.getNowTimestamp() + content;

        policyOrder.setOrder_number(randomOrderNum);
        policyOrder.setName(member.getName());
        policyOrder.setPhone(member.getPhone());
        policyOrder.setAdd_time(DateUtil.getNowTimestamp());
        policyOrderService.save(policyOrder);

        return ResultGenerator.successResult();
    }

    //购买政策
    @PostMapping("/policyBuy")
    public Result policyBuy(@RequestBody PolicyOrder policyOrder, HttpServletRequest request) throws Exception {
        if (policyOrder.getUser_id() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Member member = memberService.findById(policyOrder.getUser_id());
        //调起支付
        Random random = new Random();
        String content = String.valueOf(random.nextInt(9999) % (9999 - 1000 + 1) + 1000);
        String randomOrderNum = DateUtil.getNowTimestamp() + content;
        //准备商家数据包
        HashMap<String, Object> attachMap = new HashMap<>();
        attachMap.put("user_id", policyOrder.getUser_id());
        attachMap.put("policy_id", policyOrder.getPolicy_id());
        attachMap.put("unit_id", policyOrder.getUnit_id());
        attachMap.put("charge_id", policyOrder.getCharge_id());
        attachMap.put("buy_type", policyOrder.getBuy_type());
        SortedMap<Object, Object> resultMap = PayCommonUtil.wxPay(WXAPPConfigUtil.APPID, WXAPPConfigUtil.MCH_ID, randomOrderNum, Double.valueOf(policyOrder.getAmount()), member.getWechat_id(), "购买政策", "JSAPI", "", JSONObject.fromObject(attachMap).toString(), WXAPPConfigUtil.POLICY_BUY_NOTIFY_URL, request);

        return ResultGenerator.successResult(resultMap);

    }

    //购买政策回调
    @RequestMapping("/policyBuyNotify")
    public void policyBuyNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map packageParams = PayCommonUtil.getWXNotifyData(request, WXAPPConfigUtil.API_KEY);
        String resXml = "";
        if (packageParams != null) {
            //------------------------------
            //处理业务开始
            //------------------------------

            FileWriter writer = new FileWriter(Constants.PATH_IMAGE_PATH + "wx_notify.txt", true);

            if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
                // 这里是支付成功
                //////////执行自己的业务逻辑////////////////

                try {
                    Double money = Double.valueOf((String) packageParams.get("total_fee")) / 100;
                    String randomOrderNum = (String) packageParams.get("out_trade_no");
                    String attach = (String) packageParams.get("attach");
                    JSONObject attachObj = JSONObject.fromObject(attach);
                    String user_id = attachObj.getString("user_id");
                    String policy_id = attachObj.getString("policy_id");
                    String unit_id = attachObj.getString("unit_id");
                    String charge_id = attachObj.getString("charge_id");
                    String buy_type = attachObj.getString("buy_type");

                    Member member = memberService.findById(Integer.valueOf(user_id));

                    PolicyOrder policyOrder = new PolicyOrder();
                    policyOrder.setUser_id(member.getId());
                    if (buy_type.equals("1")) {
                        policyOrder.setPolicy_id(Integer.valueOf(policy_id));
                    } else if (buy_type.equals("2")) {
                        policyOrder.setUnit_id(Integer.valueOf(unit_id));
                    } else if (buy_type.equals("3")) {
                        policyOrder.setCharge_id(Integer.valueOf(charge_id));
                    }
                    policyOrder.setOrder_number(randomOrderNum);
                    policyOrder.setName(member.getName());
                    policyOrder.setPhone(member.getPhone());
                    policyOrder.setBuy_type(Integer.valueOf(buy_type));
                    policyOrder.setBuy_form(2);
                    policyOrder.setAmount(money.toString());
                    policyOrder.setAdd_time(DateUtil.getNowTimestamp());
                    policyOrderService.save(policyOrder);


                    if (policyOrder.getBuy_type() == 1) {
                        Policy policy = policyService.findById(policyOrder.getPolicy_id());
                        if (policy.getUser_id() != null) {
                            Member member1 = memberService.findById(policy.getUser_id());
                            member1.setBalance(String.valueOf(Double.valueOf(member1.getBalance()) + (money / 2.0)));
                            memberService.update(member1);
                            Message message = new Message();
                            message.setUser_id(member1.getId());
                            message.setMessage_type(5);
                            message.setMessage_content(member.getNickname() + "购买了您发布的政策");
                            message.setMessage_port(1);
                            message.setAdd_time(DateUtil.getNowTimestamp());
                            messageService.save(message);
                        }
                    } else if (policyOrder.getBuy_type() == 2) {
                        Unit unit = unitService.findById(policyOrder.getUnit_id());
                        if (unit.getUser_id() != null) {
                            Member member1 = memberService.findById(unit.getUser_id());
                            member1.setBalance(String.valueOf(Double.valueOf(member1.getBalance()) + (money / 2.0)));
                            memberService.update(member1);
                            Message message = new Message();
                            message.setUser_id(member1.getId());
                            message.setMessage_type(5);
                            message.setMessage_content(member.getNickname() + "购买了您发布的政策");
                            message.setMessage_port(1);
                            message.setAdd_time(DateUtil.getNowTimestamp());
                            messageService.save(message);
                        }
                    } else if (policyOrder.getBuy_type() == 3) {
                        Charge charge = chargeService.findById(policyOrder.getCharge_id());
                        if (charge.getUser_id() != null) {
                            Member member1 = memberService.findById(charge.getUser_id());
                            member1.setBalance(String.valueOf(Double.valueOf(member1.getBalance()) + (money / 2.0)));
                            memberService.update(member1);
                            Message message = new Message();
                            message.setUser_id(member1.getId());
                            message.setMessage_type(5);
                            message.setMessage_content(member.getNickname() + "购买了您发布的政策");
                            message.setMessage_port(1);
                            message.setAdd_time(DateUtil.getNowTimestamp());
                            messageService.save(message);
                        }
                    }
                } catch (Exception e) {
                    writer.write(e.toString());
                    writer.flush();
                    writer.close();
                }

                //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
                resXml = PayCommonUtil.setXML("SUCCESS", "OK");

            } else {
                resXml = PayCommonUtil.setXML("FAIL", "报文为空");
            }
        } else {
            resXml = PayCommonUtil.setXML("FAIL", "报文为空");
        }
        //------------------------------
        //处理业务完毕
        //------------------------------
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }


}
